package com.yc.class_attendance;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.yc.nfc.ComBean;
import com.yc.nfc.MyFunc;
import com.yc.nfc.SerialHelper;
import com.yc.nfc.TLV;

import java.security.InvalidParameterException;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * 项目名：智慧课牌
 * Created by ${LiuShaoQing} on 2017/8/31.
 * Time: 2017/8/31 14:43
 */

public class TestSerPortActivity extends BaseNewActivity {
    public static final String HEZILOG = "hejianguo";
    private SerialHelper mCom;
    private int iRecLines = 0;
    private TextView et_1;
    private DispQueueThread DispQueue;
    private byte[] RecvData = new byte[512];
    byte[] UUID = new byte[4]; //??????
    private boolean validDataFlag = false;

    Button btnStart,btnRead;

    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    String mLicenceUrl = "http://120.237.110.51:8040/licencecard.dat";//测试

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.test_serport);
        mCom = new SerialHelper() {
            @Override
            protected void onDataReceived(ComBean ComRecData) {
                // TODO Auto-generated method stub
                DispQueue.AddQueue(ComRecData);
                //Log.i(STORAGE_SERVICE, "222222222222222");
            }
        };
        try {
            mCom.open();

        } catch (InvalidParameterException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        DispQueue = new DispQueueThread();
        DispQueue.start();

        et_1 = (TextView) findViewById(R.id.et_1);
        btnRead= (Button) findViewById(R.id.btnRead);


        btnStart = (Button) findViewById(R.id.btnStart);
        {
            mCom = new SerialHelper() {
                @Override
                protected void onDataReceived(ComBean ComRecData) {
                    // TODO Auto-generated method stub
                    DispQueue.AddQueue(ComRecData);
                    //Log.i(STORAGE_SERVICE, "222222222222222");
                }
            };
            try {
                mCom.open();

            } catch (InvalidParameterException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SecurityException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            DispQueue = new DispQueueThread();
            DispQueue.start();
        }
        btnStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
             mCom.doSetParam();
            }
        });
        btnRead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mCom.doReadParm();
            }
        });


    }


    private class DispQueueThread extends Thread {
        private Queue<ComBean> QueueList = new LinkedList<ComBean>();

        @Override
        public void run() {
            super.run();
            while (!isInterrupted()) {
                final ComBean ComData;
                while ((ComData = QueueList.poll()) != null) {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            DispRecData(ComData);
                        }
                    });
                    try {
                        Thread.sleep(100);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                }
            }
        }

        public synchronized void AddQueue(ComBean ComData) {
            QueueList.add(ComData);
        }
    }

    private void DispRecData(ComBean ComRecData) {

        StringBuilder sMsg = new StringBuilder();
        sMsg.append(ComRecData.sRecTime);
        sMsg.append("[");
        sMsg.append(ComRecData.sComPort);
        sMsg.append("]");

        sMsg.append("[Hex] ");


        if (!isValid()) {
            setRecvData(ComRecData.bRec);
            //解析 TLV 格式数据

            setValidDataFlag(true);
        }


        Log.d("res", MyFunc.ByteArrToHex(ComRecData.bRec));
        //测试
//        List<TLV> mlist= MyFunc.ByteArrToHexBB(ComRecData.bRec);
//        if(mlist!=null && mlist.size()>1){
//            Log.d("res", mlist.get(1).value);
//            if("F8ED9274".equals(mlist.get(1).value)){
//                Log.d("res","刷卡成功");
//            }else{
//                Log.d("res","刷卡失败");
//            }
//        }
        //
        sMsg.append(MyFunc.ByteArrToHex(ComRecData.bRec));


        sMsg.append("\r\n");
        et_1.append(sMsg);
//    	 Log.i(STORAGE_SERVICE,sMsg.toString());
        iRecLines++;
        //editTextLines.setText(String.valueOf(iRecLines));
        if ((iRecLines > 10))//??500????????
        {
            et_1.setText("");
            //editTextLines.setText("0");
            iRecLines = 0;
        }

    }
    void setRecvData(byte[] recv)
    {
        for(int i= 0;i < recv.length;i++)
        {
            RecvData[i] = recv[i];
        }
    }
    private void setValidDataFlag(boolean b) {
        // TODO Auto-generated method stub
        validDataFlag = b;
    }
    private boolean isValid() {
        // TODO Auto-generated method stub
        return validDataFlag;
    }
}
